package com.weavernorth.action.application;



import com.engine.kq.biz.KQBalanceOfLeaveBiz;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 请假流程控制
 */
public class Application implements Action {
    private static Log log = LogFactory.getLog(Application.class);
    @Override
    public String execute(RequestInfo requestInfo) {


        //多条明细表的第一个开始、结束日期的月份
        StringBuffer strMonth = new StringBuffer();
        BaseBean bb = new BaseBean();
        RecordSet rsTbale = new RecordSet();
        RecordSet rsDetail = new RecordSet();
        RecordSet rsDetailTwo = new RecordSet();
        RecordSet rsCount = new RecordSet();
        //获取请求ID
        String strLcId = requestInfo.getRequestid();
        //获取表单名称
        //String strTableName = requestInfo.getRequestManager().getBillTableName();

        RecordSet rsTable=new RecordSet();
        String strTableName ="";
        rsTable.execute("select tablename  from workflow_bill where id = (select formid from workflow_base where id=(select workflowid from workflow_requestbase  where requestid='"+strLcId+"') and isbill=1)");
        if(rsTable.next()){
            strTableName=rsTable.getString("tablename");
        }
        bb.writeLog("tablename的值是：" + strTableName);

//    //查询主表的数据
//      String strMainSql = "select * from "+strTableName+" where requestid='"+strLcId+"'";
//      bb.writeLog("查询主表数据的sql："+strMainSql);
//      rsMain.executeQuery(strMainSql);
//      String strQjlx="";
//      if(rsMain.next()){
//          //获取请假类型的值
//          strQjlx=Util.null2String(rsMain.getString("qjlx"));
//        }
        //查询明细表数据的sql
        String strSqlDetail = "select * from " + strTableName + "_dt1 d," + strTableName + " s  where d.mainid=s.id  and  s.requestid = '" + strLcId + "'";
        bb.writeLog("查询明细表数据的sql：" + strSqlDetail);
        rsDetail.executeQuery(strSqlDetail);

        //获取当前日期
        Date date = new Date();
        //格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formatDate = sdf.format(date);
        bb.writeLog("当前日期：" + formatDate);
        Date parseDate = null;
        try {
            parseDate = sdf.parse(formatDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //获取第一个明细表日期的月份：
        String strSqlDetailTwo = "select * from " + strTableName + "_dt1 d," + strTableName + " s  where d.mainid=s.id  and  s.requestid = '" + strLcId + "'";
        rsDetailTwo.executeQuery(strSqlDetailTwo);
        //转换为天数的基数
        long longRank = 1000 * 24 * 60 * 60;
        //查询请假类型，明细表的所有请假类型都是一样的；
        String strQjlx = "";
        if (rsDetailTwo.next()) {
            //获取开始日期
            String strKsrqTwo = Util.null2String(rsDetailTwo.getString("detail_fromDate"));
            bb.writeLog("获取到的第一个明细数据的日期：" + strKsrqTwo);
            //转换格式
            Date dateKsrqTwo = null;
            try {
                dateKsrqTwo = sdf.parse(strKsrqTwo);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //获取月份值
            Calendar calender = Calendar.getInstance();
            calender.setTime(dateKsrqTwo);
            strMonth.append(String.valueOf(calender.get(Calendar.MONTH) + 1));
            bb.writeLog("开始日期的第一个月份值：" + strMonth);
            //获取请假类型
            strQjlx = Util.null2String(rsDetailTwo.getString("qjlx"));
        }

        //循环对明细表数据处理：
        while (rsDetail.next()) {
            //获取开始、结束日期
            String strKsrq = Util.null2String(rsDetail.getString("detail_fromDate"));
            String strJsrq = Util.null2String(rsDetail.getString("detail_toDate"));
            //转换格式
            Date dateKsrq = null;
            try {
                dateKsrq = sdf.parse(strKsrq);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Date dateJsrq = null;
            try {
                dateJsrq = sdf.parse(strJsrq);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long longKsMs = dateKsrq.getTime() - parseDate.getTime();
            //开始日期与当前日期相差天数
            int intKsDay = Integer.parseInt(String.valueOf(longKsMs / longRank));
            bb.writeLog("开始日期与当前日期相差天数：" + intKsDay);
            //结束日期与当前日期相差天数
            long longJsMs = dateJsrq.getTime() - parseDate.getTime();
            int intJsDay = Integer.parseInt(String.valueOf(longJsMs / longRank));
            bb.writeLog("结束日期与当前日期相差天数：" + intJsDay);
            log.info("当前请假类型:"+strQjlx);
            //判断请假日期是否在30个自然日内
            if(!"7".equals(strQjlx)&&!"8".equals(strQjlx)) {
                if (intKsDay > 30 || intJsDay > 30) {
                    requestInfo.getRequestManager().setMessagecontent("请假日期或结束日期须在与当前日期的30个自然日内");
                    //不符合规定阻止流程提交
                    return FAILURE_AND_CONTINUE;
                }
            }

            //zm 修改
            //查询明细表条数的sql：
//            String strSqlCount = "select count(*) as num  from " + strTableName + "_dt1 d," + strTableName + " s  where d.mainid=s.id  and  s.requestid = '" + strLcId + "'";
//            bb.writeLog("查询明细表条数的sql：" + strSqlCount);
//            rsCount.executeQuery(strSqlCount);
//            if (rsCount.next()) {
//                int intNum = Integer.parseInt(Util.null2String(rsCount.getString("num")));
//                if (intNum > 1) {
                    //获取月份值
                    Calendar calender = Calendar.getInstance();
                    calender.setTime(dateKsrq);
                    //开始日期的月份
                    String strBeginMonth = String.valueOf(calender.get(Calendar.MONTH) + 1);

                    bb.writeLog("获取月份值：" + strBeginMonth);
                    //结束日期的月份  zm
                    String strEndMonth="";
                    if(!"".equals(strJsrq)){
                        strEndMonth=strJsrq.split("-")[1];
                    }
                    //如果月份为02,变为2
                    if(!"".equals(strEndMonth)){
                        strEndMonth=Integer.parseInt(strEndMonth)+"";
                    }
                    bb.writeLog("请假结束月:"+strEndMonth+",结束日期:"+strJsrq);
                    //同一条记录不可跨月
                    if(!strBeginMonth.equals(strEndMonth)&&("3".equals(strQjlx)||"14".equals(strQjlx)||"4".equals(strQjlx)||"5".equals(strQjlx)||"13".equals(strQjlx))||"15".equals(strQjlx)){
                        requestInfo.getRequestManager().setMessagecontent("请假只能申请同一个月的");
                        //不符合规定阻止流程提交
                        return FAILURE_AND_CONTINUE;
                    }
                    //如果其他明细表数据月份与第一条数据的月份不一致

                    if (!strMonth.toString().equals(strBeginMonth)||!strMonth.toString().equals(strEndMonth)) {
                        if(("3".equals(strQjlx)||"14".equals(strQjlx)||"4".equals(strQjlx)||"5".equals(strQjlx)||"13".equals(strQjlx))||"15".equals(strQjlx)) {
                            requestInfo.getRequestManager().setMessagecontent("多条明细数据时，所有的请假开始、结束日期应在同一月份");
                            //不符合规定阻止流程提交
                            return FAILURE_AND_CONTINUE;
                        }
                    }

//                }
//            }

            //判断请假类型值是否为事假
            if (strQjlx.equals("6")) {
                String strName = Util.null2String(rsDetail.getString("detail_resourceId"));
                bb.writeLog("请假人的姓名：" + strName);
                bb.writeLog("当前日期：" + formatDate);
                //年假
                String strHoliday = KQBalanceOfLeaveBiz.getRestAmount(strName, "2", strKsrq);
                bb.writeLog("年假字符串：" + strHoliday);
                double douHoliday = Double.parseDouble(strHoliday);
                bb.writeLog("年假dou类型：" + douHoliday);
                //查询当前人被冻结的年假
                double douFreezeYear = getFrzeeLeave(strName, "2");
                //得到剩余的年假
               double douSy= douHoliday-douFreezeYear;
               bb.writeLog("减去冻结的年假:"+douSy);

                //调休假
                String strHolidayTwo = KQBalanceOfLeaveBiz.getRestAmount(strName, "5", strKsrq);
                double douHolidayTwo = Double.parseDouble(strHolidayTwo);
                bb.writeLog("调休假：" + strHolidayTwo);
                //查询当前人被冻结的年假
                double douFreezeExchange = getFrzeeLeave(strName, "5");
                double douSyExchange= douHolidayTwo-douFreezeExchange;
                bb.writeLog("减去冻结的调休假:"+douSyExchange);
                //查询被冻结的调休假
                //判断是否有年假或者调休假
                if (douSy > 0.5) {
                    requestInfo.getRequestManager().setMessagecontent("存在年假:" + douSy + "天，您不能提交事假");
                    //不符合规定阻止流程提交
                    return FAILURE_AND_CONTINUE;
                }

                if (douSyExchange > 0.5) {
                    requestInfo.getRequestManager().setMessagecontent("存在调休假:" + douSyExchange + "，您不能提交事假");
                    //不符合规定阻止流程提交
                    return FAILURE_AND_CONTINUE;
                }
                long longMs = dateJsrq.getTime() - dateKsrq.getTime();
                long longDay = longMs / longRank;
                bb.writeLog("请假类型为事假时，请假天数为" + longDay);
                if (longDay >= 30) {
                    requestInfo.getRequestManager().setMessagecontent("请假类型为事假时，不能超过30个自然日");
                    //不符合规定阻止流程提交
                    return FAILURE_AND_CONTINUE;
                }
            }

        }

        return SUCCESS;
    }


    /**
     * 查询被冻结的假期天数
     *
     * @param strUserid 用户id,strLeaveType 假期类型
     * @return 冻结的假期
     */
    public static double getFrzeeLeave(String strUserid, String strLeaveType) {

        //返回值
        double douDays = 0.0;
        //数据库操作
        RecordSet rs = new RecordSet();
        String sql = "select sum(duration)  duration from KQ_ATT_VACATION where resourceid=? and newleavetype=? and status='1'";
        log.info("查询当期是否有被冻结的假期:"+sql+",strUserid:"+strUserid+",strLeaveType:"+strLeaveType);
        rs.executeQuery(sql, strUserid, strLeaveType);
        if (rs.next()) {
            douDays = Util.getDoubleValue(rs.getString("duration"),0);
        }
        log.info("返回被冻结的天数:"+douDays);
        return douDays;
    }


}